<template>
  <div>
    <!-- 面包屑  -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible=true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type='expand'>
          <template slot-scope="scope">
            <el-row :class="['bdbuttom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 通过循环渲染二级权限 -->

                <el-row :class="[ i2 === 0 ? '':'bdtop','vcenter']" v-for=" (item2,i2) in item1.children" :key='item2.id'>
                  <el-col :span="6">
                    <el-tag @close="removeRightById(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">

                    <!-- 三级权限 -->
                    <el-col>
                      <el-tag @close="removeRightById(scope.row,item3.id)" closable v-for=" (item3,i3) in item2.children" :key='item3.id' type="warning">{{item3.authName}}</el-tag>
                    </el-col>

                  </el-col>
                </el-row>

              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="序列" type='index'></el-table-column>
        <el-table-column label='角色名称' prop='roleName'></el-table-column>
        <el-table-column label='角色描述' prop='roleDesc'></el-table-column>
        <el-table-column label='操作' width="300px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button @click="showEditRoles(scope.row.id)" size="mini" type='primary' icon="el-icon-edit">编辑</el-button>
            <!-- 删除 -->
            <el-button @click="removeRolesById(scope.row.id)" size="mini" type='danger' icon="el-icon-delets">删除</el-button>
            <!-- 分配权限 -->
            <el-button @click="showSetRightDialog(scope.row)" size="mini" type='warning' icon="el-icon-setting">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色弹窗 -->
    <el-dialog title="添加角色" @close="addRolesClosed" :visible.sync="addRolesVisible" width="50%">
      <!-- 主体区 -->
      <!-- :rules是表单的认证规则，需要搭配prop使用，来确定该行的验证用哪个 -->
      <el-form :model="addRoles" :rules="addRolesRules" ref="addRolesRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesButton">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" @close="editRolesClosed" :visible.sync="editRolesVisible" width="50%">
      <!-- 主体区 -->
      <!-- :rules是表单的认证规则，需要搭配prop使用，来确定该行的验证用哪个 -->
      <el-form :model="editRoles" :rules="editRolesRules" ref="editRolesRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesButton">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog @close='setRightDialogClosed' title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <el-tree ref="treeRef" :default-checked-keys='defKeys' default-expand-all node-key='id' show-checkbox :data="rightlist" :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'Roles',
  components: {},
  data () {
    return {

      roleslist: [], //所有角色列表数据
      addRolesVisible: false,//控制弹窗显示与隐藏
      editRolesVisible: false,
      addRoles: {         //添加角色的对象
        roleName: '',
        roleDesc: '',
      },
      addRolesRules: { //添加角色验证规则
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 12, message: '用户名的长度在1~12个字符之间', trigger: 'blur' }
        ],
        roleDesc: [

        ]
      },
      editRoles: {//修改数据该id的全部数据


      },
      editRolesRules: {//修改角色验证规则
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 12, message: '用户名的长度在1~12个字符之间', trigger: 'blur' }
        ],
        roleDesc: [
        ]
      },
      setRightDialogVisible: false,//控制分配角色对话框显示与隐藏
      rightlist: [],//放分配角色按钮 的所有数据
      treeProps: {//树形控件的属性绑定对象
        label: 'authName',
        children: 'children'
      },
      //默认分配权限选中的节点id
      defKeys: [],
      roleId: '',//当前即将分配权限的角色的id



    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    //请求列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败') }
      this.roleslist = res.data
    },
    //添加角色的弹窗 退出清空数据
    addRolesClosed () {
      this.$refs.addRolesRef.resetFields()
    },
    //添加角色的弹窗 确定按钮
    addRolesButton () {
      this.$refs.addRolesRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post('roles', this.addRoles)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        //隐藏对话框
        this.addRolesVisible = false
        //重新刷新对话框信息
        this.getRolesList()

      })
    },
    //获取修改角色对话框的数据
    async showEditRoles (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editRoles = res.data

      this.editRolesVisible = true
    },
    //修改角色对话框的关闭 就会重置数据
    editRolesClosed () {
      this.$refs.editRolesRef.resetFields()
    },
    //修改角色的确定按钮
    editRolesButton (id) {
      this.$refs.editRolesRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.put('roles/' + this.editRoles.roleId, { roleName: this.editRoles.roleName, roleDesc: this.editRoles.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('更新用户失败')
        this.editRolesVisible = false
        this.getRolesList()
        this.$message.success('更新用户成功')
      })
    },
    //根据id删除数据
    async removeRolesById (id) {
      //先弹窗再删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'//图标
      }).catch(err => err)
      //用户点击确定会返回字符串 confirm
      //用户点击取消会返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getRolesList()
    }
    ,//三级权限弹窗是否删除
    async removeRightById (role, rightId) {
      //先弹窗再删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'//图标
      }).catch(err => err)
      //用户点击确定会返回字符串 confirm
      //用户点击取消会返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)//  用` `（esc下面那个键） ${} 代表获取当前参数的动态数据，不用写死
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      role.children = res.data

    },
    //展时分配角色对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightlist = res.data
      //获取三级权限的方法
      console.log(role);
      this.getLeafKeys(role, this.defKeys)

      //获取所以权限数据
      this.setRightDialogVisible = true
    },
    //通过递归的方式获取全部三级权限的id到defKeys数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        //如果不包含children就说明 他是三级权限
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr));

    },
    //监听分配权限对话框的关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    //点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys()
        , ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      console.log(idStr);
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false

    }
  }

}
</script>
<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbuttom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>